package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * @author: lcz
 * @date: Created in 14:42 2020/9/25
 * @description:
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;
    private Executor executor = new SimpleExecutor();

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectAll(String statementId, Object... params) throws Exception {
        MappedStatement statement = configuration.getMappedStatementMap().get(statementId);
        return executor.query(configuration, statement, params);
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectAll(statementId, params);
        if (objects.size() > 1) {
            throw new RuntimeException("the return result is not unique");
        }
        return (T) objects.get(0);
    }

    @Override
    public int update(String statementId, Object... params) throws Exception {
        if (StringUtils.isBlank(statementId)) {
            throw new RuntimeException("statementId must not be empty");
        }
        MappedStatement statement = configuration.getMappedStatementMap().get(statementId);
        return executor.executeUpdate(configuration, statement, params);
    }

    @Override
    public int insert(String statementId, Object... params) throws Exception {
        return this.update(statementId, params);
    }

    @Override
    public int delete(String statementId, Object... params) throws Exception {
        return this.update(statementId, params);
    }

    @Override
    public void close() throws SQLException {
        executor.close();
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            //使用JDK动态代理为DAO接口生成代理对象，并返回
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //方法名
                String methodName = method.getName();
                //类全限定名
                String className = method.getDeclaringClass().getName();
                //statementId：namespace.id  用 className.methodName 代替
                //约定mapper中的namespace与dao类全限定名一致，id和dao中对应的方法名一致
                String statementId = className + "." + methodName;
                MappedStatement statement = configuration.getMappedStatementMap().get(statementId);
                switch (statement.getSqlCommandType()) {
                    case INSERT:
                        return insert(statementId, args);
                    case UPDATE:
                        return update(statementId, args);
                    case DELETE:
                        return delete(statementId, args);
                    case SELECT:
                        //获取被调用方法的返回值类型
                        Type genericReturnType = method.getGenericReturnType();
                        //判断是否进行了 泛型类型参数化
                        if (genericReturnType instanceof ParameterizedType) {
                            List<Object> objects = selectAll(statementId, args);
                            return objects;
                        }
                        return selectOne(statementId, args);
                    default:
                        throw new RuntimeException("Unknown execution statementId for: " + statementId);
                }
            }
        });
        return (T) proxyInstance;
    }
}
